<template>
  <div class="app-container">
    <el-button
      :loading="downloadLoading"
      class="handle-button"
      @click="exportExcel(followupData)"
      icon="el-icon-download"
      type="primary"
    ></el-button>
    <el-table
      :data="tables.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      id="out-table"
      @filter-change="filterTagTable"
      border
    >
      <el-table-column prop="tDate" label="上次回访日期" min-width="110px" align="center" v-if="local==0"></el-table-column>
      <el-table-column
        prop="mDate"
        label="上次回访日期"
        min-width="110px"
        align="center"
        v-else-if="local==1"
      ></el-table-column>
      <el-table-column prop="name" label="学员姓名" min-width="100px" align="center"></el-table-column>
      <el-table-column prop="class" label="班级" min-width="100px" align="center"></el-table-column>
      <el-table-column prop="manager" label="项目经理" min-width="100px" align="center"></el-table-column>
      <el-table-column prop="teacher" label="班主任" min-width="100px" align="center"></el-table-column>
      <el-table-column align="center" prop="phone" label="手机号" min-width="110px"></el-table-column>
      <el-table-column
        align="center"
        prop="status"
        min-width="100px"
        label="状态"
        :filters="[{text: '正式', value: 0}, {text: '转中心', value: 1}, {text: '休学', value: 2}, {text: '脱产', value: 3}, {text: '结课', value: 4}, {text: '退费', value: 5}]"
        :column-key=" 'status' "
      >
        <template slot-scope="scope">{{ scope.row.status | statusFilter }}</template>
      </el-table-column>
      <el-table-column align="center" min-width="120px" v-if="local!=2">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="请输入搜索条件" />
        </template>
        <template slot-scope="scope">
          <el-button
            title="回访"
            type="success"
            icon="el-icon-chat-dot-round"
            size="mini"
            circle
            @click="handleFollow(scope.row)"
          ></el-button>
          <el-button
            title="详情"
            @click="handleMessage(scope.row)"
            size="mini"
            type="info"
            circle
            icon="el-icon-tickets"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加、修改学员回访 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      title="添加回访"
      :before-close="closeDialog"
    >
      <el-form ref="followForm" :model="form">
        <el-form-item :label="form.name+' 回访信息'">
          <el-input type="textarea" v-model="form.desc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="followStudent('followForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页器 -->
    <div class="block" style="margin-top:15px" v-if="followupData.length>10">
      <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 侧消息 -->
    <el-drawer
      title="学员更多信息"
      :visible.sync="messageBox"
      direction="rtl"
      size="50%"
      :xs="24"
      :sm="24"
    >
      <el-collapse v-model="activeName" accordion style="padding:0 15px">
        <el-collapse-item title="学员回访记录" name="1">
          <!-- 第一个 -->
          <el-table
            :data="messageBoxData"
            border
            max-height="500"
            style="width: 100%"
          >
            <el-table-column prop="date" label="日期" width="100"></el-table-column>
            <el-table-column prop="visitor" label="回访者" width="100"></el-table-column>
            <el-table-column prop="content" label="回访内容"></el-table-column>
            <el-table-column width="60" align="center">
              <template slot-scope="scope">
                <el-button
                  v-if="local.username==scope.row.visitor || local.position==2"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  @click="deleteFollow(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <div class="block" style="margin-top:15px" v-if="messageBoxData.length>10">
            <el-pagination
              align="center"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="messageBoxData.length"
            ></el-pagination>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: "",
      downloadLoading: false,
      dialogFormVisible: false,
      followupData: [],
      oldData: [],
      form: {
        name: "",
        desc: ""
      },
      textarea: "",
      // 首访表字段信息
      tallForm: {
        education: "",
        objective: "",
        specialty: "",
        JobNature: "",
        other: ""
      },
      // 学员更多信息
      messageBox: false,
      activeName: "1",
      fromdata: { type: [] },
      messageBoxData: [],
      // 判断 权限
      local: localStorage.position,
      // 分页
      currentPage: 1, // 默认第一页
      pageSize: 10 // 每页大小默认值
    };
  },
  created() {
    this.reload();
  },
  watch: {
    // 检测表格数据过滤变化，自动跳到第一页
    tables() {
      this.currentPage = 1;
    }
  },
  computed: {
    // 搜索过滤
    tables() {
      const search = this.search;
      if (search) {
        return this.followupData.filter(dataNews => {
          return Object.keys(dataNews).some(key => {
            return String(dataNews[key])
              .toLowerCase()
              .includes(search.toLowerCase());
          });
        });
      }
      return this.followupData;
    },
    // 总条数
    total() {
      return this.tables.length;
    }
  },
  methods: {
    reload() {
      this.followupData = [];
      this.axios
        .get("/student", {
          params: {
            position: localStorage.position,
            username: localStorage.username
          }
        })
        .then(res => {
          const start = new Date();
          start.setTime(
            new Date(new Date().getFullYear(), new Date().getMonth(), 1)
          );
          for (var i = 0; i < res.data.data.length; i++) {
            var end = "";
            var date = "";
            if (localStorage.position == 0) {
              //班主任
              date = res.data.data[i].tDate;
              end = new Date(res.data.data[i].tDate);
            } else {
              //项目经理
              date = res.data.data[i].mDate;
              end = new Date(res.data.data[i].mDate);
            }
            if (end.getTime() < start.getTime()) {
              this.followupData.push(res.data.data[i]);
              this.oldData.push(res.data.data[i]);
            } else if (date == "") {
              this.followupData.push(res.data.data[i]);
              this.oldData.push(res.data.data[i]);
            }
          }
        });
    },
    // 打开添加回访弹框
    handleFollow(item) {
      this.dialogType = "followup";
      this.dialogFormVisible = true;
      this.form.class = item.class;
      this.form.name = item.name;
    },
    // 添加回访学员信息
    followStudent(formName) {
      var name = this.form.name;
      var visitor = localStorage.username;
      var desc = this.form.desc;
      var cs = this.form.class;
      this.$refs[formName].validate(valid => {
        if(!desc){ 
          this.$notify({
            title: "回访内容不能为空！",
            message: "请输入回访内容",
            type: "error"
          });
          return 
        }
        if (valid) {
          this.axios
            .post(
              "/student/follow",
              `class=${cs}&name=${name}&visitor=${visitor}&content=${desc}&position=${localStorage.position}`
            )
            .then(res => {
              if (res.data.ok == 1) {
                this.$notify({
                  title: "添加成功",
                  message: `${name} 添加回访成功`,
                  type: "success"
                });
                this.closeDialog();
                this.reload();
                this.dialogFormVisible = false;
              } else {
                this.$notify({
                  title: "添加失败",
                  message: res.data.msg,
                  type: "error"
                });
                this.form.desc = "";
              }
            });
        } else {
          this.$notify({
            title: "添加失败",
            message: res.data.msg,
            type: "error"
          });
          this.form.desc = "";
        }
      });
    },
    // 打开学员更多信息
    handleMessage(item) {
      this.messageBox = true;
      this.getFollow(item);
    },
    // 获取学员回访信息
    getFollow(item) {
      this.messageBoxData = [];
      console.log(item);
      this.axios
        .get("/student/getFollow", {
          params: { name: item.name}
        })
        .then(res => {
          this.messageBoxData=res.data.data;
          console.log(res.data);
          // for (var i = 0; i < res.data.data.length; i++) {
          //   if (res.data.data[i].name === item.name) {
          //     this.messageBoxData.push(res.data.data[i]);
          //   }
          // }
          console.log(this.messageBoxData);
        });
    },
    // 删除学员回访信息
    deleteFollow(item) {
      this.$confirm(`是否删除此条学员回访记录`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.axios
            .post("/student/deleteFollow", `id=${item.id}&name=${item.name}`)
            .then(res => {
              if (res.data.ok == 1) {
                this.$message({
                  type: "success",
                  message: res.data.msg
                });
                this.getFollow(item);
              } else {
                this.$message.error(res.data.msg);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 关闭清空form数据
    closeDialog() {
      for (var item in this.form) {
        this.form[item] = "";
      }
      this.dialogFormVisible = false;
    },
    // 筛选
    filterTagTable(filters) {
      var newData = this.followupData;
      this.getAll(filters, newData); // 筛选所选项下的所有数据，需要调用后端接口
    },
    getAll(filters, newData) {
      this.followupData = [];
      for (var i = 0; i < newData.length; i++) {
        if (newData[i].status == filters.status[0]) {
          this.followupData.push(newData[i]);
        }
      }
      if (filters.status[0] == undefined) {
        this.followupData = this.oldData;
      }
    },
    // 分页
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  }
};
</script>

<style>
.handle-button {
  width: 50px;
  height: 50px;
  position: fixed;
  right: 15px;
  border-radius: 6px 0 0 6px !important;
  z-index: 999999;
  color: #fff;
}
</style>